<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">通知管理</span>
        </div>
      </template>

      <!-- 操作按钮区域 -->
      <el-row :gutter="10" class="mb-4">
        <el-col :span="1.5">
          <el-button type="primary" icon="Plus" @click="handleAddMessage">发布新通知</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="messageList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" align="center" label="序号" />
        <el-table-column prop="id" label="ID" width="60" align="center" />
        <el-table-column prop="content" label="通知内容" min-width="300" />
        <el-table-column prop="isRead" label="状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isRead === 1 ? 'success' : 'warning'">
              {{ scope.row.isRead === 1 ? '已读' : '未读' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220">
          <template #default="scope">
            <el-button 
              type="primary" 
              v-if="scope.row.isRead === 0" 
              size="small" 
              icon="Edit" 
              @click="handleEditMessage(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              type="success" 
              v-if="scope.row.isRead === 0" 
              size="small" 
              icon="Check" 
              @click="handleMarkRead(scope.row)"
            >
              标记已读
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              icon="Delete" 
              @click="handleDeleteMessage(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加/修改对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="通知内容" prop="content">
            <el-input 
              type="textarea" 
              v-model="form.content" 
              placeholder="请输入通知内容" 
              rows="6" 
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="通知对象" prop="userIds">
            <el-select
              v-model="form.userIds"
              placeholder="请选择接收人"
              multiple
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.userName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitMessage">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listMessage, addMessage, updateMessage, delMessage } from '../../api/message'
import { listUsertable } from '../../api/usertable'

// 表格数据
const messageList = ref([])
const userList = ref([])
const loading = ref(false)

// 表单参数
const form = reactive({
  id: undefined,
  content: '',
  userIds: []
})

const defaultForm = { ...form } // 保存默认表单状态

// 弹窗控制
const open = ref(false)
const title = ref('')
const formRef = ref(null)

// 表单校验规则
const rules = {
  content: [{ required: true, message: '请输入通知内容', trigger: 'blur' }],
  userIds: [{ required: true, message: '请选择接收人', trigger: 'change' }]
}

// 获取数据列表
const getList = async () => {
  loading.value = true
  try {
    const res = await listMessage()
    messageList.value = res
  } catch (error) {
    console.error('获取通知列表失败:', error)
    ElMessage.error('获取通知列表失败')
  } finally {
    loading.value = false
  }
}

// 获取用户列表
const getUserList = async () => {
  try {
    const res = await listUsertable()
    userList.value = res
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 表单重置
const reset = () => {
  formRef.value?.resetFields()
  Object.assign(form, defaultForm) // 重置为默认表单状态
}

// 新增按钮操作
const handleAddMessage = () => {
  reset()
  title.value = '新增通知'
  open.value = true
}

// 编辑通知（补充编辑功能）
const handleEditMessage = (row) => {
  reset() // 重置表单
  form.id = row.id
  form.content = row.content
  form.userIds = [...row.userIds] // 浅拷贝数组
  title.value = '编辑通知'
  open.value = true
}

// 删除按钮操作
const handleDeleteMessage = (row) => {
  ElMessageBox.confirm('确认删除该通知记录吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await delMessage(row.id)
    ElMessage.success('删除成功')
    getList()
  }).catch(() => {})
}

// 标记已读
const handleMarkRead = async (row) => {
  try {
    await updateMessage({ id: row.id, isRead: 1 }) // 只传递必要参数
    ElMessage.success('已标记为已读')
    getList()
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('操作失败')
  }
}

// 提交表单（处理新增和编辑）
const submitMessage = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) { // 编辑场景
          await updateMessage(form)
          ElMessage.success('通知更新成功')
        } else { // 新增场景
          console.log(form)
          await addMessage(form)
          ElMessage.success('通知发布成功')
        }
        open.value = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 取消操作
const cancel = () => {
  open.value = false
  reset()
}

// 页面加载时获取数据
onMounted(() => {
  getUserList()
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.mb-4 {
  margin-bottom: 16px;
}

.dialog-footer {
  text-align: right;
}
</style>